package com.atguigu.gmall.common.interceptor;

import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.bo.UserIdBo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 1、编写一个 HandlerInterceptor
 * 2、指定拦截器拦截的请求；
 *    1）、编写一个配置类，实现 WebMvcConfigurer 接口
 *    2）、在配置类中，指定拦截器规则
 *
 */
public class AuthInterceptor implements HandlerInterceptor {



    //Controller 目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserIdBo userIdBo = new UserIdBo();

        String userId = AuthContextHolder.getUserId(request);
        if(!StringUtils.isEmpty(userId)){
            long userIdLong = Long.parseLong(userId);
            userIdBo.setUserId(userIdLong);
        }

        String tempId = AuthContextHolder.getUserTempId(request);
        if(!StringUtils.isEmpty(tempId)){
            userIdBo.setUserTempId(tempId);
        }

        //给当前整个线程放入用户id的Bo对象
        AuthContextHolder.setUserIdBo(userIdBo);

        return true;
    }

    //Controller执行之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //移除
        AuthContextHolder.removeUserIdBo();
    }
}
